#include "widget.h"
#include "ui_widget.h"
#include<QTcpSocket>
#include<QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //1.修改窗口标题
    this->setWindowTitle("服务器");

    //创建QTcpServer的实例
    tcpserver = new QTcpServer(this);


    //通过信号槽，指定如何处理连接
    connect(tcpserver,&QTcpServer::newConnection,this,&Widget::processConnection);


    //绑定并监听窗口号
    bool ret = tcpserver->listen(QHostAddress::Any,9090);
    if(!ret)
    {
        QMessageBox::critical(this,"服务器启动失败",tcpserver->errorString());
        exit(1);
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::processConnection()
{
    //通过tcpServer  拿到一个 socket对象，通过这个对象和客户端进行通信
    QTcpSocket * clientSocket = tcpserver->nextPendingConnection();
    QString log = "("+clientSocket->peerAddress().toString() + ":"+QString::number(clientSocket->peerPort())+"]客户端上线";
    ui->listWidget->addItem(log);

    //通过信号槽，来处理客户端发来的请求
    connect(clientSocket,&QTcpSocket::readyRead,this,[=](){
       //读取请求数据
       QString request  =  clientSocket->readAll();

       //根据请求处理响应
       const QString& response =process(request);


       //响应写到客户端
       clientSocket->write(response.toUtf8());

       //把上述信息记录到日志中
       QString log = "["+ clientSocket->peerAddress().toString()+ ":"+ QString::number(clientSocket->peerPort())+"]"
        +"req: "+ request+ ",resp " + response;
       ui->listWidget->addItem(log);
    });


    //通过信号槽,处理客户端断开连接的情况
    connect(clientSocket,&QTcpSocket::disconnected,this,[=](){
        //把断开连接的信息通过日志显示出来
        QString log = "("+clientSocket->peerAddress().toString() + ":"+QString::number(clientSocket->peerPort())+"]客户端下线";
        ui->listWidget->addItem(log);
        //手动释放 clientSocket

    //        delete clientSocket;
        clientSocket->deleteLater();
    });
}


//回显服务器
QString Widget::process(const QString request)
{
    return  request;
}

